package com.adcc.ags.gms.core.controller;

import com.adcc.ags.gms.core.entity.SysUser;
import com.adcc.ags.gms.core.service.CoreService;
import com.adcc.ags.gms.core.service.LoginService;
import com.adcc.ags.gms.core.util.AppConfiguration;
import com.adcc.ags.gms.core.util.Constant;
import com.adcc.ags.gms.core.util.LogFactory;
import com.adcc.ags.gms.core.vo.MenuVO;
import com.adcc.ags.gms.core.vo.ResultState;
import com.adcc.ags.gms.core.vo.ResultVO;
import com.adcc.ags.gms.gw.service.SysConfigurationService;
import com.adcc.ags.gms.gw.service.UserMonitorService;
import com.adcc.ags.gms.gw.vo.UserMonitorVO;
import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Handles requests for the application home page.
 */
@Controller
public class CoreController {

    private static final Logger logger = LoggerFactory.getLogger(CoreController.class);

    @Autowired
    private AppConfiguration configuration;

    @Autowired
    private CoreService coreService;

    @Autowired
    private SysConfigurationService sysConfigurationService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private UserMonitorService userMonitorService;

    @Autowired
    private LogFactory log;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String start() {
        return "/login/login";
    }

    /**
     * 加载首页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/load", method = RequestMethod.GET)
    public String load() {
        return "/core/index";
    }

    @RequestMapping(value = "/loadDefaultPage", method = RequestMethod.GET)
    public @ResponseBody Map<String, String> loadDefaultPage(HttpSession session) {
        try {
            Map<String, String> map = Maps.newLinkedHashMap();
            //根据用户类型进行跳转
            SysUser u = (SysUser) session.getAttribute("user");
            if (u.getType() == 0) {
                map.put("url", sysConfigurationService.getValue(Constant.ADMIN_DEFAULT_URL));
            } else {
                map.put("url", sysConfigurationService.getValue(Constant.MONITORUSER_DEFAULT_URL));
            }
            return map;
        } catch (Exception ex) {
            log.error(CoreController.class, "loadDefaultPage() error", ex);
            return null;
        }
    }

    /**
     * 获取菜单
     * @param session
     * @return
     */
    @RequestMapping(value = "/findMenu", method = RequestMethod.GET)
    public @ResponseBody ResultVO findMenu(HttpSession session) {
        ResultVO resultVO = new ResultVO();
        SysUser user = (SysUser) session.getAttribute("user");
        try {
            Optional<List<MenuVO>> optional = coreService.findMenuItemByUserType(user.getType());
            if (optional.isPresent()) {
                if(optional.get().size() > 0){
                    resultVO.getData().put("menuVO",optional.get());
                }
            }else{
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
            return resultVO;
        } catch (Exception e) {
            log.error(CoreController.class, "findMenu() error", e);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
            return resultVO;
        }
    }

    /**
     * 根据URI进行跳转
     *
     * @return
     */
    @RequestMapping(value = "/turn", method = RequestMethod.GET)
    public  String login(String url) {
        return url;
    }


    /**
     * 获取用户监控告警数
     *
     * @return
     */
    @RequestMapping(value = "/getUserMonitorWarning", method = RequestMethod.GET)
    public @ResponseBody ResultVO getUserMonitorWarning() {
        ResultVO resultVO = new ResultVO();
        int userWarningNum = 0;
        List<Integer> userWarningNumList = new ArrayList<>();
        try {
            Optional<List<UserMonitorVO>> list = userMonitorService.findAllUserMonitor();
            if (list.isPresent() && list.get().size() > 0) {
                for (UserMonitorVO userMonitorVO : list.get()) {
                    if (userMonitorVO.getState() == 1) {
                        userWarningNum = userWarningNum + 1;
                    }
                }
                userWarningNumList.add(userWarningNum);
                resultVO.getData().put("userMonitorWarningNum", userWarningNumList);
            } else {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason("数据库暂无数据或查询失败！");
            }
            return resultVO;
        } catch (Exception e) {
            log.error(CoreController.class, "getUserMonitorWarning() error", e);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason("服务器访问失败");
            return resultVO;
        }
    }

    /**
     * 退出系统
     *
     * @param session Session
     * @return
     */
    @RequestMapping(value = "/logout")
    public @ResponseBody String logout(HttpSession session, String password) {
        if (session != null) {
            try {
                SysUser user = (SysUser) session.getAttribute("user");
                user.setPassword(password);
                Optional<ModelAndView> optional =loginService.verifyUser(user, session);
                if(optional.get().getModel().get("error")==null){
                    //清除session
                    session.invalidate();
                    return "SUCCESS";
                }
            } catch (Exception ex) {
                log.error(CoreController.class,"logout() error",ex);
            }
        }
        return "FAILURE";
    }

    @RequestMapping(value = "/getTime")
    public @ResponseBody String getTime() {
        return  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }
}
